package com.dpteam.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dpteam.bean.ImportInfo;
import com.dpteam.bean.UserInfo;
import com.dpteam.model.News;
import com.dpteam.model.User;
import com.dpteam.service.MemberService;
import com.dpteam.service.NewsService;
import com.dpteam.service.StorageService;
import com.dpteam.service.UserManageService;
import com.dpteam.util.Constant;
import com.dpteam.util.Page;
import com.dpteam.util.TransformUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import com.dpteam.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by YangZhi on 2016/1/11.
 */
@Controller
@RequestMapping("manage")
public class ManagerController {
    private Logger logger = LoggerFactory.getLogger(ManagerController.class);
    @Resource
    private UserManageService userManageService;

    @Resource
    private NewsService newsService;

    @Resource
    private StorageService storageService;

    @Resource
    MemberService memberService;


    /**
     * 用户管理
     */
    @RequestMapping("findByUserId")
    public String findByUserId() {

        return null;
    }

    /**
     * 按角色查询用户
     *
     * @param request
     * @return
     */

    @RequestMapping("findByRole")
    @ResponseBody
    public String findByRole(HttpServletRequest request) {

        int roleId = 0;
        try {
            roleId = Integer.parseInt(request.getParameter("roleId"));
        } catch (Exception e) {
            return "{\"isSuccess\":false,\"msg\"：\"角色Id不正确\"}";
        }
        List<User> userList = userManageService.findUserByRoleId(roleId);
        List<UserInfo> userInfoList = new ArrayList<>();
        for (User u : userList) {
            userInfoList.add(TransformUtil.fromUser(u));
        }
        logger.info(userInfoList.toString());
        return "{\"isSuccess\":true,\"data\":" + userInfoList.toString() + "}";
    }

    /**
     * 用户信息修改
     */
    @RequestMapping("updateUser")
    @ResponseBody
    public String updateUser(int userId, String userName, String userEmail, String userPhoneNumber) {
        logger.info("updateUser:userId={},userName={},userEmail={},userPhoneNumber={}", userId, userName, userEmail, userPhoneNumber);
        userManageService.updateUser(userId, userName, userEmail, userPhoneNumber);
        return "{\"isSuccess\":true}";
    }

    /**
     * 删除用户
     */
    @RequestMapping("deleteUser")
    @ResponseBody
    public String deleteUser(HttpServletRequest request) {
        UserInfo admin = (UserInfo) request.getSession().getAttribute(Constant.currentUserKey);
        int userId = 0;
        try {
            userId = Integer.parseInt(request.getParameter("userId"));
        } catch (Exception e) {
            return "{\"isSuccess\":false,\"msg\":\"用户Id不存在！\"}";
        }
        userManageService.deleteUserById(userId);
        return "{\"isSuccess\":true}";
    }

    /**
     * 发布公告
     */
    @RequestMapping("publishNews")
    public String publishNews(HttpServletRequest request) {
        UserInfo admin = (UserInfo) request.getSession().getAttribute(Constant.currentUserKey);
        User user = new User();
        user.setId(admin.getId());
        String title = request.getParameter("title");
        String message = request.getParameter("message");
        News news = new News();
        news.setUser(user);
        news.setTitle(title);
        news.setMessage(message);
        news.setPublishTime(LocalDateTime.now());
        newsService.addNews(news);
        return "makeNotice";
    }

    /**
     * 入库查询
     */
    @RequestMapping("findStorageAllPage")
    @ResponseBody
    public String findStorageAllPage(HttpServletRequest request, int curPage, int pageSize) {
        logger.info("findStorageAllPage:curPage={},pageSize={}", curPage, pageSize);
        Page page = new Page(pageSize, curPage);
        List<ImportInfo> productList = storageService.findImportInfoAllPage(page);
        Map map = new HashMap<>();
        map.put("productList", productList);
        map.put("page", page);
        return JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect).toString();
    }

    /**
     * 会员修改
     */
    @RequestMapping("memberModify")
    public String memberModify(int memberId, String memberName, String memberPhoneNumber, String IDCardNo) {
        logger.info("memberModify:memberId={},memberName={},memberPhoneNumber={},IDCardNo={}", memberId, memberName, memberPhoneNumber, IDCardNo);
        // 校验
        boolean check = StringUtil.isNotEmpty(memberName)
                && InputCheckUtil.isIDCartNo(IDCardNo)
                && InputCheckUtil.isPhone(memberPhoneNumber);
        if (!check) {
            // 校验失败，重新刷新界面
            logger.info("校验失败");
            return "forward:../link/memberSearch";
        }

        memberService.update(memberId, memberName, memberPhoneNumber, IDCardNo);
        return "forward:../link/memberSearch";
    }

    /**
     * 图像上传
     */
    @RequestMapping("/uploadPhoto")
    public String uploadPhoto(MultipartFile fileField, HttpServletRequest request) {
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String dir = request.getServletContext().getRealPath("/resources/img");
        try {
            userManageService.updateUserInfo(fileField, phone, email, dir);
        } catch (Exception e) {
            if (e != null) e.printStackTrace();
            return "error";
        }
        return "personDetails";
    }

    @RequestMapping("/addUser")
    public String addUser(UserInfo userInfo) {
        userManageService.addUser(userInfo);
        return "addUser";
    }
}
